package com.qingkai.onlineshop.presentation.cart

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.qingkai.onlineshop.R
import com.qingkai.onlineshop.data.AppDatabase
import com.qingkai.onlineshop.data.relations.ItemWithPics
import com.qingkai.onlineshop.presentation.dashboard.testItemWithPics
import com.qingkai.onlineshop.presentation.detail.NumButton
import org.koin.compose.koinInject

/**
 *作者：created by 89270 on 2025/6/19 10:48
 *描述：
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CartScreen(isPreview: Boolean = false, upPress: () -> Unit = {}) {
    var carts by remember { mutableStateOf(emptyList<ItemWithPics>()) }
    val appDatabase = if (isPreview) {
        AppDatabase.getInstance(LocalContext.current)
    } else {
        koinInject()
    }
    LaunchedEffect(Unit) {
        carts = if (isPreview) {
            List(4) { testItemWithPics }
        } else {
            appDatabase.itemDao().getRecommendedItems()
        }
    }
    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(navigationIcon = {
                Image(
                    painter = painterResource(id = R.drawable.back),
                    contentDescription = "back", modifier = Modifier
                        .clip(CircleShape)
                        .clickable {  upPress.invoke() }
                )
            }, title = { Text(text = stringResource(R.string.str_my_cart)) })
        },
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            CartList(carts = carts)
            CalculateCard()
        }
    }
}

@Composable
private fun ColumnScope.CartList(carts: List<ItemWithPics>) {
    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .weight(3f)
    ) {
        items(carts) {
            CartItem(itemWithPics = it)
        }
    }
}

@Composable
fun CartItem(itemWithPics: ItemWithPics) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
            .clip(RoundedCornerShape(12.dp))
            .background(MaterialTheme.colorScheme.primaryContainer)
            .padding(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        AsyncImage(
            model = itemWithPics.pics.firstOrNull()?.url ?: " ",
            contentDescription = itemWithPics.item.title,
            modifier = Modifier
                .size(80.dp)
                .aspectRatio(1f)
                .clip(RoundedCornerShape(12.dp))
                .background(MaterialTheme.colorScheme.background),
            placeholder = painterResource(id = R.drawable.img_1_1),
            error = painterResource(id = R.drawable.img_1_1)
        )
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text(
                text = itemWithPics.item.title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            Text(text = "$${itemWithPics.item.price}", color = Color.Gray)
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "$${itemWithPics.item.price * 2}",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                NumButton(
                    modifier = Modifier
                        .height(30.dp)
                        .width(100.dp)
                        .clip(CircleShape)
                        .shadow(4.dp)
                        .background(MaterialTheme.colorScheme.primary),
                    count = 2,
                    onIncrease = {},
                    onDecrease = {}
                )
            }
        }
    }
}

@Composable
private fun ColumnScope.CalculateCard() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .weight(1f)
            .padding(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        CalculateItem(
            label = stringResource(R.string.str_subtotal),
            price = "$280"
        )
        CalculateItem(
            label = stringResource(R.string.str_free_delivery),
            price = "$10"
        )
        CalculateItem(
            label = stringResource(R.string.str_total_tax),
            price = "$3"
        )
        HorizontalDivider()
        CalculateItem(
            label = stringResource(R.string.str_total),
            price = "$293"
        )
        Button(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            onClick = { }) { Text(text = "Check Out") }
    }

}

@Composable
fun CalculateItem(label: String, price: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Bold
        )
        Text(
            text = price,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Bold
        )
    }
}

@Preview(showBackground = true)
@Composable
fun CartScreenPreview() {
    CartScreen(isPreview = true)
}